const isNumber = require('lodash/isNumber')
const cloud = require('wx-server-sdk')
const appid = process.env.appid //你的小程序appid
const secret = process.env.secretkey //你的小程序secret

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const ERROR_MSG = {
  500: '服务器错误',
  401: '登录过期',
  404: '未找到资源',
  4001: '重复提交'
}
class CustomError extends Error {
  constructor(code, msg) {
    super()
    this.code = code || 500
    this.msg = msg || ERROR_MSG[code] || 'unknown error'
  }
  getCodeMsg() {
    return {
      code: this.code,
      msg: this.msg
    }
  }
}
// 增加额外command功能
const _ = db.command
// 1. 获取数据库引用
const TcbRouter = require('tcb-router')

exports.main = async (event, context) => {

  const app = new TcbRouter({ event })
  const { OPENID, UNIONID } = cloud.getWXContext()
  app.use(async (ctx, next) => {
    //适用于所有的路由
    ctx.data = {} //声明data为一个对象
    try {
      ctx.body = {}
      ctx.body.code = 0
      await next()
    } catch (err) {
      console.log(err, 'err'.repeat(10))
      console.log(ctx)
      if (err instanceof CustomError) {
        const res = err.getCodeMsg()
        ctx.body = {}
        ctx.body.code = res.code || 500
        ctx.body.msg = res.msg
      } else if (err instanceof Error) {
        console.log(err)
        ctx.body = {}
        ctx.body.code = 500
        ctx.body.msg = err.message
      } else if (typeof err === 'string') {
        ctx.body = {}
        ctx.body.code = 500
        ctx.body.msg = err
      } else {
        ctx.body = {}
        ctx.body.code = res.code || 500
        ctx.body.msg = res.msg
      }
    }
  })
  if (event.event === "recommended") {
    try {
      // await db.collection("recommended_daily").
      // 1，获取数据的总个数
      let count = await db.collection('recommended_daily').count()
      count = count.total
      // 2，通过for循环做多次请求，并把多次请求的数据放到一个数组里
      let all = []
      for (let i = 0; i < count; i += 100) { //自己设置每次获取数据的量
        let list = await db.collection('recommended_daily').skip(i).get()
        all = all.concat(list.data);
      }
      // 3,把组装好的数据一次性全部返回
      return all;
    } catch (error) {
      return error
    }
  }

  //  收藏页面内容的查询(用于收藏键的使用)
  if (event.event === "find_recommended") {
    const { logotype } = event
    try {
      return await db.collection("collection").where({
        logotype: logotype
      }).get()
    } catch (error) {
      return error
    }
  }

  //收藏文章
  app.router("add_collection", async (ctx, next) => {
    const { title, content, collection_person, id, picture } = event
    try {
      await db.collection("collection").add({
        data: {
          title: title,
          content: content,
          collection_person: collection_person,
          collection_time: new Date(),
          picture: picture,
          // 特殊id
          logotype: id,
          openid: OPENID
        }
      })
    } catch (error) {
      return error
    }
  })

  //展示收藏页面的东西,根据openid进行来从数据库中找出该用户的所有收藏信息(用户)
  app.router("find_collection", async (ctx, next) => {
    const { openid } = event
    try {
      await db.collection("collection").where({
        openid
      }).get().then(res => {
        return ctx.body = {
          data:res
        }
      })
    } catch (error) {
      console.log(error)
    }
  })
  //删除收藏页面中的不想要的东西
  app.router("remove_collection", async (ctx, next) => {
    //   特殊id
    const { id } = event
    try {
      await db.collection("collection").where({
        // 特殊id(暂定)
        logotype: id
      }).remove()
    } catch (error) {
      console.log(error)
    }
  })

  return app.serve()
}